<?php

namespace Orqlog\YacampaignDrawLaravel\Domain\Repository;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Orqlog\Yacampaign\Domain\Model\PrizeInterface;
use Orqlog\YacampaignDrawLaravel\Domain\Model\Prize;
use Orqlog\Yacampaign\Domain\Repository\PrizeRepositoryInterface;
use Orqlog\YacampaignDrawLaravel\Contracts\CampaignPrizeContract;

class PrizeRepository extends Model implements PrizeRepositoryInterface
{
    
    use SoftDeletes, RepositoryTraits;
    protected $table = 'yadc_prizes'; // The corresponding table name


    public function createPrize(array $data):int
    {
        $prize = $this->makePrize($data);
        $prize = $this->addItem($prize);
        return $prize->getId();
    }

    public function getPrizesForCampaign(int $campaignId) :array
    {
        $campaignPrize = app()->make(CampaignPrizeContract::class);
        $bindings = $campaignPrize->where('campaign_id', '=', $campaignId)->get();
        $result = [];
        foreach ($bindings as $bind) {
            array_push($result, $this->findById($bind->prize_id));
        }
        return $result;
    }
    
    /**
     * Persist the prize (create / update)
     */
    public function add(Prize $prize): Prize
    {
        return $this->addItem($prize);
    }

    public function findById(int $id) :PrizeInterface
    {
        $item = $this->find($id);
        return $this->makePrize(json_decode(json_encode($item), true));
    }

    /**
     * Constitute Draw prize from raw data
     */
    public function makePrize(array $data) : PrizeInterface
    {
        $prize = new Prize();
        if (is_array($data)) $data = (Object) $data;
        if (isset($data->id)) $prize->setId($data->id);
        if (isset($data->title)) $prize->setTitle($data->title);

        return $prize;
    }

    /**
     * Convert from DrawCampaign to this ORM format
     */
    protected function makeItem(Prize $prize, $item = null) : Object
    {
        $item = is_null($item) ? new self() : $item;

        $item->title = $prize->getTitle();

        return $item;
    }

    /**
     * remove DrawCampaign
     */
    public function remove(int $prizeId) :void
    {
        $this->where('id', '=', $prizeId)->delete();
    }

}